// ==UserScript==
// @name         Linux do 在话题列表下方显示话题内容
// @namespace    http://tampermonkey.net/
// @version      1.7
// @description  在话题/搜索列表下方显示话题内容，点击重新加载内容开始加载
// @match        https://linux.do/*
// @grant        GM_xmlhttpRequest
// @grant        GM_registerMenuCommand
// @grant        GM_unregisterMenuCommand
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_addStyle
// @run-at       document-end
// @require      https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js
// ==/UserScript==

(function () {
    'use strict';

    require("discourse/routes/topic").default.disableReplaceState = true;

    // --- 全局常量 ---
    const POST_DATA_KEY = 'linuxdo_post_history_v3';
    const THRESHOLD_KEY = 'linuxdo_post_threshold_v3';
    const laset_id = 'linuxdo_post_laset_id';
    const DEFAULT_THRESHOLD = 2;

    let storedPosts = null;
    let savaPosts = {}
    let groupedPosts = null;
    init()
    // 过滤7天内的数据并按date分组
    var today = new Date();
    const sevenDaysAgo = new Date(today);
    sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7); // 计算7天前的日期

    var theDate = getFormattedDate();
    var yesterday = theDate[1];


    //加载摘要的间隔事件, 单位毫秒
    var waitTime = 1000;

    //新增内容
    var addDiv = '<div is_insert="1" style="background: #C6FFC6;width: 60vw;"></div>';


    async function init() {
        const storedObj = await GM_getValue(POST_DATA_KEY, {});
        console.log('storedObj size', Object.keys(storedObj).length)
        // 直接使用 storedObj 作为 storedPosts
        storedPosts = storedObj;
        groupedPosts = new Map();
        for (const id in storedPosts) {
            const post = storedPosts[id];
            const postDate = new Date(post.date);
            if (postDate >= sevenDaysAgo) { // 只保留7天内的数据
                if (!groupedPosts.has(post.date)) {
                    groupedPosts.set(post.date, []);
                }
                groupedPosts.get(post.date).push(post);
            } else { // 删除7天前的数据
                delete storedPosts[id];
            }
        }
    }
    async function finish() {
        // 直接使用 storedPosts
        await GM_setValue(POST_DATA_KEY, storedPosts);
        //向http://127.0.0.1:5000/savePost 发送fetch post请求
        fetch("http://127.0.0.1:5000/savePost", {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
                data: savaPosts
            })
        });
    }

    async function getPreviewContent(topicId, notNeedContent = true) {
        try {

            // Check if content is already cached
            //console.log("notNeedContent:", notNeedContent);
            //console.log("storedPosts[topicId]:", storedPosts[topicId]);
            //console.log("storedPosts[content]:", storedPosts[topicId]["content"]);
            if (notNeedContent && storedPosts[topicId]) {
                //console.log("Content found in cache:", contentCache[linkHref]);
                if (storedPosts[topicId]["content"]) {
                    return storedPosts[topicId]["content"];
                }
            }
            let url = `https://linux.do/t/topic/${topicId}.json`;

            //console.log("linkHref url: " + linkHref);
            // Fetch content from the link URL
            var response = await fetch(url);
            if (!response.ok) {
                throw new Error("Network response was not ok");
            }

            let jsonData = await response.json();
            let cookedContent = jsonData.post_stream.posts[0].cooked;

            await sleep(waitTime);
            // Return the extracted cooked content
            return cookedContent;
        } catch (error) {
            console.error("Error fetching link preview content:", error);
            return null;
        }
    }

    function ascPost() {
        // 获取当前页面的URL, 加上升序排列
        let currentUrl = window.location.href;

        // 判断URL是否已经包含?ascending=true
        if (!currentUrl.includes('?ascending=true')) {
            // 如果URL已经有其他参数，使用&符号添加新的参数
            if (currentUrl.includes('?')) {
                currentUrl += '&ascending=true';
            } else {
                // 如果URL没有任何参数，使用?符号添加新的参数
                currentUrl += '?ascending=true';
            }

            // 重新加载页面，并且包含新的URL
            window.location.href = currentUrl;
        }
    }

    async function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms))
    }


    async function work(notNeedContent = false) {
        // 查找所有的<tr>标签，并筛选出有data-topic-id属性的标签
        const rows = $('tr[data-topic-id]');
        if (rows && rows.length === 0) return;
        try {
            for (const tr of rows) {
                let $tr = $(tr);
                let topicId = $tr.attr('data-topic-id');
                //设置基本信息
                let postData = {}
                if (storedPosts[topicId]) {
                    postData = storedPosts[topicId]
                } else {
                    postData = getPostBaseData(tr)
                }
                storedPosts[topicId] = postData;
                savaPosts[topicId] = postData;
                // 判断是否是隐藏的
                if ($tr.is(':hidden') || notNeedContent) {
                    continue;
                }

                let cookedContent = await getPreviewContent(topicId);
                //console.log("url: " + url, "cookedContent:" + cookedContent);
                if (cookedContent) {
                    postData.content = cookedContent;
                    //数据是否已插入
                    var nextTr = $tr.next('tr')
                    if (nextTr && nextTr.find('div[is_insert="1"]').length > 0) {
                        continue;
                    }
                    // 在<tr>标签最后插入新的<div>
                    //$tr.appendChild(newCell1);
                    // 在新的 tr 中插入包含 cookedContent 的 div
                    let $newRow = $('<tr></tr>');
                    let $newDiv = $(addDiv); // 创建新的 div 元素
                    $newDiv.html(cookedContent); // 设置 div 的 HTML 内容
                    $newRow.append($newDiv);
                    $tr.after($newRow);
                }
            }
        } catch (error) {
            console.error('处理行时出错:', error);
        }
        finish()

    }
    function getPostBaseData(row) {
        const id = row.dataset.topicId;
        const posterElement = row.querySelector('td.posters a:first-of-type');
        const titleElement = row.querySelector('td.main-link a.title');
        const dateElement = row.querySelector('td.activity');

        if (id && posterElement && titleElement && dateElement) {
            const dateTitle = dateElement.title;
            const dateMatch = dateTitle.match(/创建日期：(\d{4} 年 \d{1,2}月 \d{1,2} 日)/);
            if (dateMatch) {
                // 提取并转换日期格式
                const originalDate = dateMatch[1];
                //补0操作
                const parts = originalDate.split(/[年月日\s]+/).filter(Boolean);
                const formattedDate = `${parts[0]}-${parts[1].padStart(2, '0')}-${parts[2].padStart(2, '0')}`;
                let post = {
                    id: id,
                    author: posterElement.dataset.userCard,
                    title: titleElement.innerText.trim(),
                    url: titleElement.href,
                    date: formattedDate
                };
                return post;
            }
        }
        return {};
    }
    async function workSearchData() {
        // 查找 class="fps-result-entries" 的 div 标签
        const fpsResultEntries = document.querySelector('.fps-result-entries');
        if (!fpsResultEntries) return;

        // 遍历下面 role="listitem" 的 div
        const listItems = fpsResultEntries.querySelectorAll('div[role="listitem"]');
        //判断是否有数据
        if (listItems && listItems.length === 0) return;

        for (let divItem of listItems) {
            // 判断是否是隐藏的
            if ($(divItem).is(':hidden')) {
                continue;
            }
            // 从 divItem 中获取 href="/t/topic/数字" 的 a 标签
            const aTag = divItem.querySelector('a[href^="/t/topic/"]');
            if (aTag) {
                // 取 href 中的数字值为 topicId
                const topicId = aTag.getAttribute('href').match(/\/t\/topic\/(\d+)/)[1];

                //console.log('url', url)
                const cookedContent = await getPreviewContent(topicId, false);

                // 移除 divItem 中 class="blurb container" 的 div
                const blurbContainer = divItem.querySelector('.blurb.container');
                if (cookedContent && blurbContainer) {
                    var $listItem = $(divItem);
                    // 查找 is_insert="1" 的 div 元素
                    var targetDiv = $listItem.find('div[is_insert="1"]');
                    // 检查是否已插入
                    if (targetDiv.length > 0) {
                        continue
                    }
                    // 将 blurbContainer 的内容替换为 cookedContent
                    let $newDiv = $(addDiv); // 创建新的 div 元素
                    $newDiv.html(cookedContent); // 设置 div 的 HTML 内容
                    $(blurbContainer).after($newDiv);
                }
            }
        }
    }

    // 添加 Tampermonkey 菜单按钮
    GM_registerMenuCommand("滚动到最后未看贴", async function () {
        let currentUrl = window.location.href;
        if (currentUrl === 'https://linux.do/latest?order=created') {
            const dateKeys = Object.keys(storedPosts);
            // 获取最后一个已读帖子的ID
            let lastReadTopicId = dateKeys[dateKeys.length - 1];
            console.log('最后一个已读帖子的ID', lastReadTopicId);
            await GM_setValue(laset_id, lastReadTopicId);
            while (1) {
                let rows = $('tr[data-topic-id]');
                if (rows.length == 0) {
                    console.log('获取帖子失败');
                    break;
                }
                let lastTr = rows.last()[0];
                let currentTopicId = parseInt($(lastTr).attr('data-topic-id'));
                if (currentTopicId > lastReadTopicId) {
                    lastTr.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    await sleep(2000);
                } else {
                    console.log('滑动到最后一个没有看的贴');
                    console.log('隐藏已看贴');
                    toggleHidePosts(true)
                    await sleep(2000);
                    console.log('加载内容');
                    work();
                    break;
                }
            }
        }
    });

    GM_registerMenuCommand("重新加载内容", function () {
        let currentUrl = window.location.href;
        if (currentUrl.includes('/search?')) {
            workSearchData()
        } else {
            work();
        }
    });
    // 添加 Tampermonkey 菜单按钮
    GM_registerMenuCommand("升序排序", function () {
        ascPost();
    });
    // 添加 Tampermonkey 菜单按钮
    GM_registerMenuCommand("搜索当日帖子", function () {
        var today = new Date();

        var toDayDate = formatDate(today)

        today.setDate(today.getDate() + 1);
        var beforeDate = formatDate(today)

        var url = 'https://linux.do/search?q=after:' + toDayDate + ' before:' + beforeDate + ' in:first order:oldest -tags:KFC,刺猬';

        window.location.href = url;
    });


    GM_registerMenuCommand("隐藏已加载帖子", () => toggleHidePosts(true));
    GM_registerMenuCommand("显示已加载帖子", () => toggleHidePosts(false));
    function toggleHidePosts(isHidden) {
        const href = window.location.href;
        const selector = href.includes('/search?') ?
            $('.fps-result-entries').find('div[role="listitem"]') :
            $('tr[data-topic-id]');
        // 记录隐藏的帖子
        selector.each(function () {
            let $this = $(this);
            let topicId;

            // 根据不同的容器获取topicId
            if ($this.is('div')) {
                topicId = $this.find('div[data-topic-id]').first().attr('data-topic-id');
            } else if ($this.is('tr')) {
                topicId = $this.attr('data-topic-id');
            }
            //console.log(topicId, totalCache[topicId])
            if (topicId && storedPosts[topicId]) {
                $this[isHidden ? 'hide' : 'show']();
                if ($this.is('tr')) {
                    $this.next('tr')[isHidden ? 'hide' : 'show']();
                }
            }
        });

    }

    GM_registerMenuCommand("滚动到上次未看帖", () => onlyHidePosts());
    async function onlyHidePosts() {
        const href = window.location.href;
        const rows = href.includes('/search?') ?
            $('.fps-result-entries').find('div[role="listitem"]') :
            $('tr[data-topic-id]');
        // 获取最后一个已读帖子的ID
        let lastReadTopicId = await GM_getValue(laset_id)
        if (!lastReadTopicId) return
        while (1) {
            if (rows.length == 0) {
                console.log('获取帖子失败');
                break;
            }
            let lastTr = rows.last()[0];
            let topicId;
            let $this = $(lastTr);
            // 根据不同的容器获取topicId
            if ($this.is('div')) {
                topicId = $this.find('div[data-topic-id]').first().attr('data-topic-id');
            } else if ($this.is('tr')) {
                topicId = $this.attr('data-topic-id');
            }
            let currentTopicId = parseInt(topicId);
            if (currentTopicId > lastReadTopicId) {
                lastTr.scrollIntoView({ behavior: 'smooth', block: 'center' });
                await sleep(2000);
            } else {
                console.log('滑动到最后一个没有看的贴');
                console.log('隐藏已看贴');
                toggleHidePosts(true)
                break;
            }
        }
    }


    function formatDate(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    }

    // 页面加载完成后执行
    $(document).ready(async function () {
        if (window.location.href.includes('linux.do/')) {
            addPrevNextBtn();
        }
        await init();
    });

    function getFormattedDate() {
        const date = new Date();
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');

        // 获取昨天的日期
        const yesterday = new Date(date);
        yesterday.setDate(date.getDate() - 1);
        const yYear = yesterday.getFullYear();
        const yMonth = String(yesterday.getMonth() + 1).padStart(2, '0');
        const yDay = String(yesterday.getDate()).padStart(2, '0');
        const beforeDate = `${yYear}-${yMonth}-${yDay}`;

        return [`${year}-${month}-${day}`, beforeDate];
    }

    //添加上/下一贴按钮
    function addPrevNextBtn() {
        // 获取标题元素
        const titleElement = document.querySelector('.title');
        // 判断是否有上/下一贴按钮
        if (document.querySelector('#myprev-topic-btn') === null) {
            // 创建上一贴按钮
            const prevButton = document.createElement('button');
            prevButton.textContent = '上一贴';
            prevButton.className = 'btn btn-prev';
            prevButton.id = 'myprev-topic-btn';
            prevButton.onclick = function () {
                prevNextTopic(true);
            };
            // 将按钮插入到标题元素右边
            titleElement.appendChild(prevButton);

        }
        if (document.querySelector('#mynext-topic-btn') === null) {
            // 创建下一贴按钮
            const nextButton = document.createElement('button');
            nextButton.textContent = '下一贴';
            nextButton.className = 'btn btn-next';
            nextButton.id = 'mynext-topic-btn';
            nextButton.onclick = function () {
                prevNextTopic(false);
            };
            // 将按钮插入到标题元素右边
            titleElement.appendChild(nextButton);
        }
        navigationBarHeight = getNavigationBarHeight();
    }

    //上一贴下一贴
    function prevNextTopic(isUp) {
        // 确定方向，isUp为true表示向上，-1代表上一个，1代表下一个
        const direction = isUp ? -1 : 1;

        // 获取所有topic行的列表
        const trs = document.querySelectorAll(".topic-list-body tr");
        const emberList = Array.from(trs).filter(tr => {
            return tr.style.display !== 'none';  // 过滤掉 display: none; 的行
        });

        // 查找第一个出现在视口中的元素
        const currentElement = emberList.find(tr => isElementPartiallyInViewport(tr));
        if (!currentElement) {
            return;
        }

        // 获取当前元素的索引位置
        const currentIndex = emberList.indexOf(currentElement);
        // 获取下一个或上一个元素的索引
        let nextIndex = currentIndex + direction;

        // 如果下一个元素存在且需要滚动，找到不是"data-topic-id"前缀的元素
        while (nextIndex >= 0 && nextIndex < emberList.length && !emberList[nextIndex].hasAttribute("data-topic-id")) {
            nextIndex += direction;
        }
        // 如果下一个合法元素存在，则进行滚动
        if (nextIndex >= 0 && nextIndex < emberList.length) {
            const nextElement = emberList[nextIndex];
            window.scrollBy(0, nextElement.getBoundingClientRect().top - navigationBarHeight);
        }
    }
    //获取导航栏高度
    function getNavigationBarHeight() {
        return document.querySelector("#ember3 > div.drop-down-mode.d-header-wrap > header > div > div").offsetHeight;
    }
    let navigationBarHeight = 0;
    //判断元素是否在可视范围内
    function isElementPartiallyInViewport(el) {
        const rect = el.getBoundingClientRect();

        const partiallyInViewport = (
            rect.top < (window.innerHeight || document.documentElement.clientHeight) &&
            rect.bottom > navigationBarHeight + 5
        );

        return partiallyInViewport;
    }


    // --- CSS 样式 (修复后) ---
    GM_addStyle(`
        #stats-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.6);
            z-index: 9998;
            display: none;
        }
        #stats-modal {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 80%;
            max-width: 800px;
            height: 80vh; /* 使用 height 而非 max-height */
            background: #f9f9f9;
            border-radius: 8px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.3);
            z-index: 9999;
            color: #333;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
            display: flex;
            flex-direction: column;
        }
        #stats-modal-header {
            padding: 15px 20px;
            border-bottom: 1px solid #ddd;
            font-size: 1.2em;
            font-weight: bold;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: #fff;
            border-top-left-radius: 8px;
            border-top-right-radius: 8px;
            flex-shrink: 0; /* 防止头部在 flex 布局中被压缩 */
        }
        #stats-modal-close {
            cursor: pointer;
            font-size: 1.5em;
            font-weight: bold;
            color: #888;
            padding: 5px;
            line-height: 1;
        }
        #stats-modal-close:hover {
            color: #000;
        }
        #stats-modal-controls {
            display: flex;
            align-items: center;
            gap: 8px;
            background: #f8f9fa;
            padding: 8px 12px;
            border-radius: 6px;
            border: 1px solid #e9ecef;
            font-size: 0.9em;
        }
        #stats-modal-controls label {
            color: #495057;
            font-weight: 500;
            margin: 0;
        }
        #days-input {
            width: 60px;
            padding: 4px 8px;
            border: 1px solid #ced4da;
            border-radius: 4px;
            font-size: 0.9em;
            text-align: center;
            background: #fff;
            transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
        }
        #days-input:focus {
            outline: none;
            border-color: #007bff;
            box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
        }
        #query-btn {
            background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
            color: white;
            border: none;
            padding: 6px 16px;
            border-radius: 4px;
            font-size: 0.9em;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
            box-shadow: 0 2px 4px rgba(0, 123, 255, 0.2);
        }
        #query-btn:hover {
            background: linear-gradient(135deg, #0056b3 0%, #004085 100%);
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0, 123, 255, 0.3);
        }
        #query-btn:active {
            transform: translateY(0);
            box-shadow: 0 2px 4px rgba(0, 123, 255, 0.2);
        }
        #stats-modal-content {
            padding: 20px;
            overflow-y: auto; /* 核心修复: 使内容区可滚动 */
            flex: 1; /* 核心修复: 占据所有剩余的垂直空间 */
            min-height: 0; /* 核心修复: 允许 flex item 在空间不足时收缩, 这是 overflow 生效的关键 */
        }
        #stats-modal-content .summary {
            margin: 0 0 15px 0;
            font-size: 1.1em;
            background-color: #e9ecef;
            padding: 10px 15px;
            border-radius: 5px;
        }
        #stats-modal-content ul {
            list-style-type: none;
            padding: 0;
            margin: 0;
        }
        #stats-modal-content .poster-item {
            background: #fff;
            border: 1px solid #ddd;
            border-radius: 5px;
            margin-bottom: 15px;
            padding: 15px;
            transition: box-shadow 0.2s;
        }
        #stats-modal-content .poster-item:hover {
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .poster-header {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }
        .poster-name {
            font-weight: bold;
            color: #0056b3;
            font-size: 1.2em;
        }
        .post-count {
            font-size: 0.9em;
            color: #fff;
            background-color: #007bff;
            margin-left: 10px;
            padding: 3px 8px;
            border-radius: 10px;
            font-weight: 500;
        }
        .date-header {
            font-weight: bold;
            color: #495057;
            font-size: 1.05em;
            margin-top: 15px;
            padding-bottom: 5px;
            border-bottom: 1px solid #eee;
        }
        .title-list {
            margin-top: 8px;
            padding-left: 20px;
            list-style-type: disc;
            color: #666;
            font-size: 0.95em;
        }
        .title-list a {
            color: #337ab7;
            text-decoration: none;
        }
        .title-list a:hover {
            text-decoration: underline;
        }
        #stats-modal-footer {
            padding: 10px 20px;
            border-top: 1px solid #ddd;
            text-align: right;
            font-size: 0.8em;
            color: #999;
            background: #fff;
            border-bottom-left-radius: 8px;
            border-bottom-right-radius: 8px;
            flex-shrink: 0; /* 防止底部在 flex 布局中被压缩 */
        }
        /* 响应式设计 */
        @media (max-width: 768px) {
            #stats-modal {
                width: 95%;
                height: 90vh;
            }
            #stats-modal-content {
                padding: 15px;
            }
        }
    `);

    // --- 菜单注册 ---
    GM_registerMenuCommand('查看高频发帖用户 (按阈值)', showStatisticsModal);
    GM_registerMenuCommand('设置发帖数阈值...', setThreshold);

    async function setThreshold() {
        const currentThreshold = await GM_getValue(THRESHOLD_KEY, DEFAULT_THRESHOLD);
        const newThresholdStr = window.prompt(
            `请输入新的发帖数阈值 (只统计发帖数大于该值的用户):`,
            currentThreshold
        );

        if (newThresholdStr === null) return;

        const newThreshold = parseInt(newThresholdStr, 10);
        if (isNaN(newThreshold) || newThreshold < 0) {
            alert('无效的输入。请输入一个非负整数。');
            return;
        }

        await GM_setValue(THRESHOLD_KEY, newThreshold);
        alert(`发帖数阈值已成功更新为: ${newThreshold}`);
    }

    async function showStatisticsModal() {
        // 显示一个加载提示，因为数据处理可能需要一点时间
        renderModal(0, [], await GM_getValue(THRESHOLD_KEY, DEFAULT_THRESHOLD), true);

        const recentPosts = await processPostData();
        const threshold = await GM_getValue(THRESHOLD_KEY, DEFAULT_THRESHOLD);
        const posterStats = analyzePosts(recentPosts);
        const frequentPosters = Object.entries(posterStats)
            .filter(([name, data]) => data.count > threshold)
            .sort(([, aData], [, bData]) => bData.count - aData.count);
        // 更新标题显示天数
        const totalCount = Object.keys(storedPosts).length;
        renderModal(totalCount, frequentPosters, threshold, false);
    }

    /**
   * 负责加载、抓取、合并、清理和保存所有帖子数据
   * @returns {Promise<Array>} 返回最近7天的帖子对象数组
   */
    async function processPostData() {
        const rows = $('tr[data-topic-id]');
        if (rows && rows.length === 0) return;
        for (const tr of rows) {
            let $tr = $(tr);
            let topicId = $tr.attr('data-topic-id');
            //设置基本信息
            let postData = {}
            if (!storedPosts[topicId]) {
                postData = getPostBaseData(tr)
                storedPosts[topicId] = postData;
                savaPosts[topicId] = postData;
            }
        }

        finish()
        return storedPosts;
    }

    /**
   * 分析帖子数据，按作者和日期进行统计
   */
    function analyzePosts(posts) {
        const stats = {};
        for (const id in posts) {
            const post = posts[id];
            if (!stats[post.author]) {
                stats[post.author] = { count: 0, postsByDate: {} };
            }
            stats[post.author].count++;
            if (!stats[post.author].postsByDate[post.date]) {
                stats[post.author].postsByDate[post.date] = [];
            }
            stats[post.author].postsByDate[post.date].push(post);
        }
        return stats;
    }

    /**
   * 渲染并显示弹窗
   */
    function renderModal(totalPostsCount, frequentPosters, threshold, isLoading = false) {
        let overlay = document.getElementById('stats-overlay');
        let modal = document.getElementById('stats-modal');

        if (!modal) {
            overlay = document.createElement('div');
            overlay.id = 'stats-overlay';
            document.body.appendChild(overlay);

            modal = document.createElement('div');
            modal.id = 'stats-modal';
            document.body.appendChild(modal);

            const close = () => {
                if (modal) modal.style.display = 'none';
                if (overlay) overlay.style.display = 'none';
            };
            overlay.addEventListener('click', close);
            modal.innerHTML = `
                <div id="stats-modal-header">
                    <span id="stats-modal-title"></span>
                    <div id="stats-modal-controls">
                        <label for="days-input">显示近</label>
                        <input type="number" id="days-input" value="7" min="1" max="365">
                        <label for="days-input">天数据</label>
                        <button id="query-btn">查询</button>
                    </div>
                    <span id="stats-modal-close" title="关闭">&times;</span>
                </div>
                <div id="stats-modal-content"></div>
                <div id="stats-modal-footer">
                    由油猴脚本 "Linux.do 高级帖子统计器" 生成
                </div>`;
            document.getElementById('stats-modal-close').addEventListener('click', close);

            // 添加查询按钮事件监听器
            document.getElementById('query-btn').addEventListener('click', async function () {
                const daysInput = document.getElementById('days-input');
                const days = parseInt(daysInput.value);

                if (isNaN(days) || days < 1) {
                    alert('请输入有效的天数（大于0的整数）');
                    return;
                }

                // 显示加载状态
                renderModal(0, [], await GM_getValue(THRESHOLD_KEY, DEFAULT_THRESHOLD), true);

                try {
                    let postsData;
                    if (days <= 7) {
                        // 使用本地存储的数据
                        postsData = await getFilteredStoredPosts(days);
                    } else {
                        // 调用API获取数据
                        postsData = await fetchPostsByDays(days);
                    }

                    const threshold = await GM_getValue(THRESHOLD_KEY, DEFAULT_THRESHOLD);
                    const posterStats = analyzePosts(postsData);
                    const frequentPosters = Object.entries(posterStats)
                        .filter(([name, data]) => data.count > threshold)
                        .sort(([, aData], [, bData]) => bData.count - aData.count);

                    // 更新标题显示天数
                    const totalCount = Object.keys(postsData).length;
                    renderModalWithDays(totalCount, frequentPosters, threshold, days);
                } catch (error) {
                    console.error('查询数据时出错:', error);
                    alert('查询数据时出错，请检查网络连接或API服务');
                }
            });
        }

        const contentDiv = document.getElementById('stats-modal-content');
        let htmlContent = '';

        if (isLoading) {
            document.getElementById('stats-modal-title').innerText = `正在加载数据...`;
            htmlContent = `<p class="summary">正在抓取并分析帖子数据，请稍候...</p>`;
        } else {
            document.getElementById('stats-modal-title').innerText = `帖子统计报告 (发帖数 > ${threshold})`;
            htmlContent = `
                <p class="summary"><strong>总览 (最近7天):</strong> 已记录 <strong>${totalPostsCount}</strong> 个不同帖子，其中 <strong>${frequentPosters.length}</strong> 位用户的发帖数大于 ${threshold}。</p>
                <ul>
            `;

            if (frequentPosters.length > 0) {
                frequentPosters.forEach(([name, data]) => {
                    htmlContent += `
                        <li class="poster-item">
                            <div class="poster-header">
                                <span class="poster-name">${escapeHtml(name)}</span>
                                <span class="post-count">发帖数: ${data.count}</span>
                            </div>
                    `;
                    const sortedDates = Object.keys(data.postsByDate).sort((a, b) => parseDateString(b) - parseDateString(a));
                    sortedDates.forEach(date => {
                        htmlContent += `<div class="date-header">${date}</div>`;
                        htmlContent += '<ul class="title-list">';
                        data.postsByDate[date].forEach(post => {
                            htmlContent += `<li><a href="${post.url}" target="_blank" rel="noopener noreferrer">${escapeHtml(post.title)}</a></li>`;
                        });
                        htmlContent += '</ul>';
                    });
                    htmlContent += `</li>`;
                });
            } else {
                htmlContent += `<li>7天内没有发帖数大于 ${threshold} 的用户。请尝试抓取更多页面或调低阈值。</li>`;
            }

            htmlContent += '</ul>';
        }

        contentDiv.innerHTML = htmlContent;
        overlay.style.display = 'block';
        modal.style.display = 'flex'; // 使用 flex 布局
    }

    // --- 辅助函数 ---
    function escapeHtml(unsafe) {
        return unsafe
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }

    function parseDateString(dateStr) {
        return new Date(dateStr);
    }

    // 获取过滤后的本地存储数据（指定天数内）
    async function getFilteredStoredPosts(days) {
        const today = new Date();
        const targetDate = new Date(today);
        targetDate.setDate(targetDate.getDate() - days);

        const filteredPosts = {};
        for (const id in storedPosts) {
            const post = storedPosts[id];
            const postDate = new Date(post.date);
            if (postDate >= targetDate) {
                filteredPosts[id] = post;
            }
        }
        return filteredPosts;
    }

    // 从API获取指定天数的帖子数据
    async function fetchPostsByDays(days) {
        try {
            const response = await fetch(`http://127.0.0.1:5001/getPostByDiffDate?diffDate=${days}`);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const data = await response.json();
            return data.data;
        } catch (error) {
            console.error('API调用失败:', error);
            throw error;
        }
    }

    // 渲染带天数信息的弹窗
    function renderModalWithDays(totalPostsCount, frequentPosters, threshold, days) {
        const contentDiv = document.getElementById('stats-modal-content');

        document.getElementById('stats-modal-title').innerText = `帖子统计报告 (发帖数 > ${threshold})`;

        let htmlContent = `
            <p class="summary"><strong>总览 (最近${days}天):</strong> 已记录 <strong>${totalPostsCount}</strong> 个不同帖子，其中 <strong>${frequentPosters.length}</strong> 位用户的发帖数大于 ${threshold}。</p>
            <ul>
        `;

        if (frequentPosters.length > 0) {
            frequentPosters.forEach(([name, data]) => {
                htmlContent += `
                    <li class="poster-item">
                        <div class="poster-header">
                            <span class="poster-name">${escapeHtml(name)}</span>
                            <span class="post-count">发帖数: ${data.count}</span>
                        </div>
                `;
                const sortedDates = Object.keys(data.postsByDate).sort((a, b) => parseDateString(b) - parseDateString(a));
                sortedDates.forEach(date => {
                    htmlContent += `<div class="date-header">${date}</div>`;
                    htmlContent += '<ul class="title-list">';
                    data.postsByDate[date].forEach(post => {
                        htmlContent += `<li><a href="${post.url}" target="_blank" rel="noopener noreferrer">${escapeHtml(post.title)}</a></li>`;
                    });
                    htmlContent += '</ul>';
                });
                htmlContent += `</li>`;
            });
        } else {
            htmlContent += `<li>${days}天内没有发帖数大于 ${threshold} 的用户。请尝试抓取更多页面或调低阈值。</li>`;
        }

        htmlContent += '</ul>';
        contentDiv.innerHTML = htmlContent;

        const overlay = document.getElementById('stats-overlay');
        const modal = document.getElementById('stats-modal');
        overlay.style.display = 'block';
        modal.style.display = 'flex';
    }

})();
